/**
 * 
 */
package com.shashi.framework.base.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.shashi.framework.base.dao.BaseDao;

/**
 * @author shashikantmore
 * 
 */
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {

	private Class<T> type;
	
	public BaseDaoImpl()	{}
	
	/**
	 * Constructor that takes the parameter to define the type of the class.
	 * 
	 * @param type
	 */
	public BaseDaoImpl(Class<T> type) {
		this.type = type;
	}

	public void add(T entity) {
		getHibernateTemplate().saveOrUpdate(entity);
	}

	@SuppressWarnings("unchecked")
	public T findById(Serializable identifier) {
		DetachedCriteria criteria = DetachedCriteria.forClass(getType()).add(Property.forName("id").eq(identifier));
		List<T> resultList = getHibernateTemplate().findByCriteria(criteria);
		T result = null;
		if ( null != resultList && resultList.size() > 0 )	{
			result = resultList.get(0);			
		}
		return result;
	}

	/**
	 * @param type
	 *            the type to set
	 */
	public void setType(Class<T> type) {
		this.type = type;
	}

	/**
	 * @return the type
	 */
	public Class<T> getType() {
		return type;
	}

	public void delete(Serializable identifier) {
		getHibernateTemplate().delete(findById(identifier));
	}

	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(String property, String value)	{
		DetachedCriteria criteria = DetachedCriteria.forClass(getType()).add(Property.forName(property).eq(value));
		return getHibernateTemplate().findByCriteria(criteria);
	}
}
